package com.gly091020.client.screen;

import com.gly091020.MathDragon;
import com.gly091020.MathDragonFun;
import com.gly091020.NetWorkingPackId;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.PlayerSkinDrawer;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.RotationAxis;
import org.lwjgl.glfw.GLFW;

import java.util.Objects;

import static com.gly091020.MathDragon.ModID;
import static com.gly091020.MathDragon._5112151111121;


public class MathScreen extends Screen {
    private final MathDragonFun.Mathematical mathProblem;
    private final Integer dragon;
    private TextFieldWidget answerField;
    private int countdownTicks; // 倒计时tick计数器
    private static int TOTAL_TICKS = MathDragon.CONFIG.answerQuestionTime * 20; //（20tick/秒）
    private int animationTick; // 动画计数器
    private final float amount;
    private final Identifier playerTexture;

    public MathScreen(MathDragonFun.Mathematical mathProblem, Integer dragonId) {
        this(mathProblem, dragonId, 0);
    }

    public MathScreen(MathDragonFun.Mathematical mathProblem, Integer dragonId, float amount) {
        super(Text.translatable("screen.math_dragon.title"));
        this.mathProblem = mathProblem;
        this.dragon = dragonId;
        TOTAL_TICKS = MathDragon.CONFIG.answerQuestionTime * 20;
        this.countdownTicks = TOTAL_TICKS; // 初始化倒计时
        this.amount = amount;
        if (MinecraftClient.getInstance().player != null) {
            this.playerTexture = MinecraftClient.getInstance().player.getSkinTexture();
        }else{
            this.playerTexture = new Identifier(ModID, "textures/gui/gly091020.jpg");
        }
    }

    @Override
    protected void init() {
        super.init();
        // 创建输入框
        this.answerField = new TextFieldWidget(
                this.textRenderer,
                this.width / 2 - 100,
                this.height / 2 - 10,
                200,
                20,
                Text.translatable("screen.math_dragon.answer")
        );
        this.answerField.setMaxLength(20);
        this.addDrawableChild(this.answerField);
        this.addSelectableChild(this.answerField);

        // 提交按钮
        this.addDrawableChild(ButtonWidget.builder(Text.translatable("screen.math_dragon.submit"), button -> checkAnswer())
                .dimensions(this.width / 2 - 50, this.height / 2 + 20, 100, 20)
                .build());

        this.answerField.setFocused(true); // 自动聚焦
        this.setFocused(this.answerField);
        if(MathDragon.CONFIG.renderGly && Objects.equals(MinecraftClient.getInstance().getSession().getUuidOrNull(), _5112151111121)){
            this.answerField.setText(Float.toString(mathProblem.Answer));
        }
    }

    @Override
    public void tick() {
        super.tick();
        // 更新倒计时
        if (countdownTicks > 0) {
            countdownTicks--;
            if (countdownTicks <= 0) {
                sendDragonPacket(false); // 时间到发送失败
                this.close();
            }
        }

        animationTick++;
    }

    private void renderTopLeftAnimation(DrawContext context) {
        if (!MathDragon.CONFIG.renderGly){return;}
        float angle = (float) (20 * Math.sin((double) animationTick / 5));

        drawRotatedTexture(context, 30, 30, angle, 1, 48, 48, playerTexture);
    }

    @Override
    public void render(DrawContext context, int mouseX, int mouseY, float delta) {
        renderBackground(context);
        super.render(context, mouseX, mouseY, delta);
        // 渲染题目
        Text problemText = Text.translatable("screen.math_dragon.mathematical",
                formatNumber(mathProblem.Num1),
                mathProblem.Symbol.getSymbolString(),
                formatNumber(mathProblem.Num2));

        context.drawCenteredTextWithShadow(
                this.textRenderer,
                problemText,
                this.width / 2,
                this.height / 2 - 40,
                0xFFFFFF
        );

        // 渲染倒计时进度条
        renderCountdownBar(context);

        // 渲染输入提示
        context.drawCenteredTextWithShadow(
                this.textRenderer,
                Text.translatable("screen.math_dragon.enter"),
                this.width / 2,
                this.height / 2 + 50,
                0xAAAAAA
        );

        renderTopLeftAnimation(context);
    }

    private void renderCountdownBar(DrawContext context) {
        // 进度条位置和尺寸
        int barWidth = this.width;
        int barHeight = 5;
        int barX = 0;
        int barY = 0;

        // 计算进度百分比
        float progress = (float) countdownTicks / TOTAL_TICKS;

        // 计算渐变颜色 - 从绿色(0xFF00FF00)到红色(0xFFFF0000)
        int startColor = 0xFF00FF00; // 绿色
        int endColor = 0xFFFF0000;   // 红色

        // 根据进度计算当前颜色
        int r = (int)(0 * progress +
                (((endColor >> 16) & 0xFF) * (1 - progress)));
        int g = (int)(((startColor >> 8) & 0xFF) * progress +
                ((0) * (1 - progress)));
        int b = 0;

        int color = 0xFF000000 | (r << 16) | (g << 8) | b;

        // 绘制进度
        int progressWidth = (int) (barWidth * progress);
        context.fill(barX, barY, barX + progressWidth, barY + barHeight, color);
    }

    @Override
    public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
        if (keyCode == GLFW.GLFW_KEY_ENTER || keyCode == GLFW.GLFW_KEY_KP_ENTER) {
            checkAnswer();
            return true;
        } else if (keyCode == GLFW.GLFW_KEY_ESCAPE) {
            sendDragonPacket(false);
            this.close();
            return true;
        }
        return super.keyPressed(keyCode, scanCode, modifiers);
    }

    private void checkAnswer() {
        try {
            float playerAnswer = Float.parseFloat(answerField.getText());
            float correctAnswer = mathProblem.Answer;

            // 允许0.01的误差范围
            sendDragonPacket(Math.abs(playerAnswer - correctAnswer) < 0.01f);
        } catch (NumberFormatException e) {
            // 无效输入处理
            sendDragonPacket(false);
        }
        this.close();
    }

    private void sendDragonPacket(boolean isCorrect) {
        PacketByteBuf buf = PacketByteBufs.create();
        buf.writeInt(dragon);
        buf.writeFloat(amount);
        Identifier packetId = isCorrect ?
                NetWorkingPackId.ToDragonRight :
                NetWorkingPackId.ToDragonWrong;
        if (isCorrect){buf.writeFloat((float) this.countdownTicks / TOTAL_TICKS);}
        ClientPlayNetworking.send(packetId, buf);
    }

    // 静态方法用于打开界面
    public static void open(MathDragonFun.Mathematical math, Integer dragon) {
        MinecraftClient.getInstance().setScreen(new MathScreen(math, dragon));
    }

    public static void open(MathDragonFun.Mathematical math, Integer dragon, float amount) {
        MinecraftClient.getInstance().setScreen(new MathScreen(math, dragon, amount));
    }

    private String formatNumber(float number) {
        return number == (int) number ?
                String.valueOf((int) number) :
                String.format("%.2f", number);
    }

    public static void drawRotatedTexture(
            DrawContext context,        // 渲染上下文
            int x, int y,              // 绘制位置(左上角)
            float rotationDegrees,     // 旋转角度(度)
            float scale,               // 缩放比例
            int width, int height,     // 纹理尺寸
            Identifier playerTexture   // 玩家贴图
    ) {
        MatrixStack matrices = context.getMatrices();
        matrices.push(); // 保存当前矩阵状态

        // 计算旋转中心（纹理中心）
        float centerX = x + (width * scale) / 2;
        float centerY = y + (height * scale) / 2;

        // 平移到旋转中心
        matrices.translate(centerX, centerY, 0);
        // 执行旋转（Z轴旋转）
        matrices.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(rotationDegrees));
        // 缩放
        matrices.scale(scale, scale, 1f);
        // 平移回渲染起点（考虑缩放后的尺寸）
        matrices.translate(-width / 2f, -height / 2f, 0);

        // 绘制纹理（使用变换后的矩阵）
        PlayerSkinDrawer.draw(context, playerTexture, 0, 0, 48, false, false);

        matrices.pop(); // 恢复矩阵状态
    }
}